package com.example.homemanager.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.google.gson.Gson;

@RestController
public class AiController {
    private static final String APPID = "c0697eb6";
    private static final String API_PASSWORD = "a081cc793912bc450a81716892c43c5c:NDA2ODkxMWEwMmUzZGZmOTA4OGY4N2M5";
    private static final String API_URL = "https://spark-api-open.xf-yun.com/v1/chat/completions";
    private static final String HEADER = "Authorization: Bearer " + API_PASSWORD;
    private static final Gson gson = new Gson();

    // 调用星火大模型
    public static String callSparkModel(String prompt) throws Exception {
        String userId = "10284711用户";
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", HEADER);
        connection.setDoOutput(true);

        // 创建最外层的JSON对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", userId);
        jsonObject.put("model", "4.0Ultra");

        // 创建messages数组
        JSONArray messagesArray = new JSONArray();

        // 拼接最新问题
        RoleContent roleContent = new RoleContent();
        roleContent.setRole("user");
        roleContent.setContent(prompt);
        messagesArray.add(roleContent);

        // 将messages数组添加到最外层的JSON对象中
        jsonObject.put("messages", messagesArray);
        // 设置stream属性为true
        jsonObject.put("stream", false);
        jsonObject.put("max_tokens", 8192);
        jsonObject.put("temperature", 0.1);

        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            byte[] input = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
            wr.write(input, 0, input.length);
        }

        // 读取响应
        try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine);
                JsonParse jsonParse = gson.fromJson(responseLine, JsonParse.class);
                List<Choices> choicesList = jsonParse.choices;
                for (Choices tempChoices : choicesList) {
                    return tempChoices.message.content;
                }
            }
            return response.toString();
        }
    }

    @PostMapping(value = "/process-message")
    public Mono<String> processMessage(@RequestBody String message) {
        return Mono.fromCallable(() -> {
            try {
                System.out.println("接收到信息+" + message);
                // 调用 AI 处理信息
                String aiResponse = callSparkModel(message + "回答问题请用中文，不要MarkDown格式，使用纯文本格式，简要回答即可}");
                System.out.println("Ai返回信息+" + aiResponse);

                // 将 Markdown 转换为纯文本
                String plainTextResponse = markdownToPlainText(aiResponse);
                return plainTextResponse;
            } catch (Exception e) {
                System.err.println("处理请求时发生错误: " + e.getMessage());
                e.printStackTrace();
                throw e;
            }
        }).onErrorReturn("Error processing message");
    }

    private String markdownToPlainText(String aiResponse) {
        if (aiResponse == null) {
            return "";
        }

        // 移除代码块
        aiResponse = aiResponse.replaceAll("```[\\s\\S]*?```", "");

        // 移除行内代码
        aiResponse = aiResponse.replaceAll("`", "");

        // 移除标题
        aiResponse = aiResponse.replaceAll("^#{1,6}\\s+", "").replaceAll("\n#{1,6}\\s+", "\n");

        // 移除列表项
        aiResponse = aiResponse.replaceAll("^[*-+]\\s+", "").replaceAll("\n[*-+]\\s+", "\n");
        aiResponse = aiResponse.replaceAll("^\\d+\\.\\s+", "").replaceAll("\n\\d+\\.\\s+", "\n");

        // 移除链接
        aiResponse = aiResponse.replaceAll("\\[([^]]+)\\]\\([^)]+\\)", "$1");

        // 移除图片
        aiResponse = aiResponse.replaceAll("!\\[([^]]*)\\]\\([^)]+\\)", "$1");

        // 移除强调（粗体、斜体）
        aiResponse = aiResponse.replaceAll("(\\*\\*|__)(.*?)(\\*\\*|__)", "$2");
        aiResponse = aiResponse.replaceAll("(\\*|_)(.*?)(\\*|_)", "$2");

        // 移除引用
        aiResponse = aiResponse.replaceAll("^>\\s+", "").replaceAll("\n>\\s+", "\n");

        // 移除水平线
        aiResponse = aiResponse.replaceAll("^-{3,}\\s*", "").replaceAll("\n-{3,}\\s*", "\n");

        // 移除 HTML 标签
        aiResponse = aiResponse.replaceAll("<[^>]*>", "");

        // 移除多余的空白行
        aiResponse = aiResponse.replaceAll("\\n{3,}", "\n\n");

        return aiResponse.trim();
    }

    static class JsonParse {
        List<Choices> choices;
    }

    static class Choices {
        Message message;
    }

    static class Message {
        String content;
    }

    static class RoleContent {
        String role;
        String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}